import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormControl, Validators, AbstractControl } from '@angular/forms';
import { Router } from '@angular/router';

// services
import { ConstantService } from '../../../../core/services/constant.service';
import { ServerService } from '../../../../core/services/server.service';
import { StorageService } from '../../../../core/services/storage.service';

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
    loginForm: FormGroup; // 登录表单
    isSpinning: boolean = false; // 过渡效果

    constructor(
        private fb: FormBuilder,
        private constant: ConstantService,
        private server: ServerService,
        private storage: StorageService,
        private router: Router
    ) {
        /**
         * 初始化登录表单
         * 用户名: userName
         * 密码: password
         */
        this.loginForm = this.fb.group({
            userName: [null, Validators.required],
            password: [null, [Validators.required, Validators.minLength(6)]],
            remember: [false]
        });
    }

    ngOnInit() {
        // 初始化表单,默认使用登录表单缓存过得用户名
        const loginForm = this.storage.getItem(this.constant.storage.loginForm);
        if (loginForm) {
            this.loginForm.controls['userName'].setValue(loginForm.userName);
            this.loginForm.controls['remember'].setValue(loginForm.remember);
        }
        
    }

    // 获取表单项
    getFormControl(name): AbstractControl {
        return this.loginForm.controls[name];
    }

    /**
     * 登录
     * @param event 
     * @param loginValue 
     */
    submitForm(event, loginValue): void {
        this.isSpinning = true;
        // 记住用户
        if (loginValue.remember) {
            this.storage.setItem(this.constant.storage.loginForm, { userName: loginValue.userName, remember: loginValue.remember });
        }
        // TODO
        // 登录功能
        
        // 跳转页面
        this.router.navigate(['main']);
    }

}
